<template>
  <div :class="classes" :style="styles">
    <div :class="messageContentClasses">
      <div :class="[baseClass + '-content-text']" v-html="content"></div>
      <div :class="[baseClass + '-content-text']" >
        <render-cell :render="renderFunc"></render-cell>
      </div>
      <a :class="[baseClass + '-close']" v-if="closable" @click="close"><Icon  type="cross" ></Icon></a>
    </div>
  </div>
</template>

<script>
import RenderCell from './render';
import Icon  from '../icon';
export default {
  components: {
    RenderCell,
    Icon
  },
  name: 'Message',
  props:{
    prefixCls: {
      type: String,
      default: ''
    },
    content: {
      type: String,
      default: ''
    },
    duration: {
      type: Number,
      default: 3
    },
    closable: {
      type: Boolean,
      default: false
    },
    render: {
      type: Function
    },
    onClose: {
      type: Function
    },
    name:{
      type: String,
      required: true
    },
    styles: {
      type: Object,
      default: function() {
        return {
          right: '50%'
        };
      }
    },
    background: {
      type: Boolean,
      default: false
    },
    msgType: {
      type: String
    }
  },
  data(){
    return{
      closeTimer:null,
    }
  },
  computed:{
    renderFunc () {
      return this.render || function () {};
    },
    baseClass () {
      return `${this.prefixCls}-item`;
    },
    classes () {
      return [
        this.baseClass,
        {
          [`${this.baseClass}-closable`]: this.closable,
          [`${this.baseClass}-with-background`]: this.background
        }
      ];
    },
    messageContentClasses () {
      return [
        `${this.baseClass}-content`,
        {
          [`${this.baseClass}-content-${this.msgType}`]: this.msgType,
          [`${this.baseClass}-content-background`]: this.background
        }
      ];
    },
  },
  mounted(){
    this.handleEnter(this.$el);
    this.clearCloseTimer();
    if(this.duration){
      this.closeTimer=setTimeout(()=>{
        this.close()
      },this.duration*1000)
    }
  },
  beforeUnmount () {
    this.handleLeave(this.$el);
    this.clearCloseTimer();
  },
  methods:{
    handleEnter (el) {         
      el.style.height = el.scrollHeight + 'px';        
    },
    handleLeave (el) { 
      // 优化一下，如果当前只有一个 Message，则不使用 js 过渡动画，这样更优美
      if ( document.getElementsByClassName('haloe-message-item').length !== 1) {
        el.style.height = 0;
        el.style.paddingTop = 0;
        el.style.paddingBottom = 0;
      }           
    },
    close(){
      this.clearCloseTimer();
      this.onClose();
      this.$parent.$parent.close(this.name);
    },
    clearCloseTimer(){
      if(this.closeTimer){
        clearTimeout(this.closeTimer);
        this.closeTimer=null;
      }
    }
  }
};
</script>
